package org.soc.timesheet.controller;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.soc.timesheet.domain.CustomersEnabled;
import org.soc.timesheet.domain.Emails;
import org.soc.timesheet.server.domain.service.EmailsService;
import org.soc.timesheet.server.domain.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.roo.addon.web.mvc.controller.json.RooWebJson;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

@RequestMapping("/emailses")
@Controller
@RooWebScaffold(path = "emailses", formBackingObject = Emails.class)
@RooWebJson(jsonObject = Emails.class)
public class EmailsController {
	


	@RequestMapping(value = "/user/{idUser}/{page}/{limit}", method = RequestMethod.GET, headers = "Accept=application/json")
    @ResponseBody
    public ResponseEntity<Page<Emails>> findByUser(@PathVariable("idUser") int idUser,@PathVariable("page") int page,@PathVariable("limit") int limit) throws Exception{
		PageRequest pageRequest = new PageRequest(page, limit);
		Page<Emails> result = emailsService.findByIdUser(idUser,pageRequest);
		
		return new ResponseEntity<Page<Emails>>(result, getHeaders(),
				HttpStatus.OK);
		
	}
	private HttpHeaders getHeaders() {
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Type", "application/json");
		return headers;
	}

	@RequestMapping(value = "/{idEmail}", method = RequestMethod.GET, headers = "Accept=application/json")
    @ResponseBody
    public ResponseEntity<String> showJson(@PathVariable("idEmail") Integer idEmail) {
        Emails emails = emailsService.findEmails(idEmail);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json; charset=utf-8");
        if (emails == null) {
            return new ResponseEntity<String>(headers, HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<String>(emails.toJson(), headers, HttpStatus.OK);
    }
	
	

	@RequestMapping(headers = "Accept=application/json")
    @ResponseBody
    public ResponseEntity<String> listJson() {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json; charset=utf-8");
        List<Emails> result = emailsService.findAllEmailses();
        return new ResponseEntity<String>(Emails.toJsonArray(result), headers, HttpStatus.OK);
    }

	@RequestMapping(method = RequestMethod.POST, headers = "Accept=application/json")
    public ResponseEntity<String> createFromJson(@RequestBody String json, UriComponentsBuilder uriBuilder) {
        Emails emails = Emails.fromJsonToEmails(json);
        emailsService.saveEmails(emails);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        RequestMapping a = (RequestMapping) getClass().getAnnotation(RequestMapping.class);
        headers.add("Location",uriBuilder.path(a.value()[0]+"/"+emails.getIdEmail().toString()).build().toUriString());
        return new ResponseEntity<String>(headers, HttpStatus.CREATED);
    }

	@RequestMapping(value = "/jsonArray", method = RequestMethod.POST, headers = "Accept=application/json")
    public ResponseEntity<String> createFromJsonArray(@RequestBody String json) {
        for (Emails emails: Emails.fromJsonArrayToEmailses(json)) {
            emailsService.saveEmails(emails);
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        return new ResponseEntity<String>(headers, HttpStatus.CREATED);
    }

	@RequestMapping(value = "/{idEmail}", method = RequestMethod.PUT, headers = "Accept=application/json")
    public ResponseEntity<String> updateFromJson(@RequestBody String json, @PathVariable("idEmail") Integer idEmail) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        Emails emails = Emails.fromJsonToEmails(json);
        emails.setIdEmail(idEmail);
        if (emailsService.updateEmails(emails) == null) {
            return new ResponseEntity<String>(headers, HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<String>(headers, HttpStatus.OK);
    }

	@RequestMapping(value = "/{idEmail}", method = RequestMethod.DELETE, headers = "Accept=application/json")
    public ResponseEntity<String> deleteFromJson(@PathVariable("idEmail") Integer idEmail) {
        Emails emails = emailsService.findEmails(idEmail);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        if (emails == null) {
            return new ResponseEntity<String>(headers, HttpStatus.NOT_FOUND);
        }
        emailsService.deleteEmails(emails);
        return new ResponseEntity<String>(headers, HttpStatus.OK);
    }

	@Autowired
    EmailsService emailsService;

	@Autowired
    UsersService usersService;

	@RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(@Valid Emails emails, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, emails);
            return "emailses/create";
        }
        uiModel.asMap().clear();
        emailsService.saveEmails(emails);
        return "redirect:/emailses/" + encodeUrlPathSegment(emails.getIdEmail().toString(), httpServletRequest);
    }

	@RequestMapping(params = "form", produces = "text/html")
    public String createForm(Model uiModel) {
        populateEditForm(uiModel, new Emails());
        return "emailses/create";
    }

	@RequestMapping(value = "/{idEmail}", produces = "text/html")
    public String show(@PathVariable("idEmail") Integer idEmail, Model uiModel) {
        uiModel.addAttribute("emails", emailsService.findEmails(idEmail));
        uiModel.addAttribute("itemId", idEmail);
        return "emailses/show";
    }

	@RequestMapping(produces = "text/html")
    public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, @RequestParam(value = "sortFieldName", required = false) String sortFieldName, @RequestParam(value = "sortOrder", required = false) String sortOrder, Model uiModel) {
        if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
            uiModel.addAttribute("emailses", Emails.findEmailsEntries(firstResult, sizeNo, sortFieldName, sortOrder));
            float nrOfPages = (float) emailsService.countAllEmailses() / sizeNo;
            uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        } else {
            uiModel.addAttribute("emailses", Emails.findAllEmailses(sortFieldName, sortOrder));
        }
        return "emailses/list";
    }

	@RequestMapping(method = RequestMethod.PUT, produces = "text/html")
    public String update(@Valid Emails emails, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, emails);
            return "emailses/update";
        }
        uiModel.asMap().clear();
        emailsService.updateEmails(emails);
        return "redirect:/emailses/" + encodeUrlPathSegment(emails.getIdEmail().toString(), httpServletRequest);
    }

	@RequestMapping(value = "/{idEmail}", params = "form", produces = "text/html")
    public String updateForm(@PathVariable("idEmail") Integer idEmail, Model uiModel) {
        populateEditForm(uiModel, emailsService.findEmails(idEmail));
        return "emailses/update";
    }

	@RequestMapping(value = "/{idEmail}", method = RequestMethod.DELETE, produces = "text/html")
    public String delete(@PathVariable("idEmail") Integer idEmail, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        Emails emails = emailsService.findEmails(idEmail);
        emailsService.deleteEmails(emails);
        uiModel.asMap().clear();
        uiModel.addAttribute("page", (page == null) ? "1" : page.toString());
        uiModel.addAttribute("size", (size == null) ? "10" : size.toString());
        return "redirect:/emailses";
    }

	void populateEditForm(Model uiModel, Emails emails) {
        uiModel.addAttribute("emails", emails);
        uiModel.addAttribute("userses", usersService.findAllUserses());
    }

	String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
        String enc = httpServletRequest.getCharacterEncoding();
        if (enc == null) {
            enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
        }
        try {
            pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
        } catch (UnsupportedEncodingException uee) {}
        return pathSegment;
    }
}
